interface LoginResponse {
    token: string;
    user: {
        id: string;
        username: string;
    };
}

document.addEventListener('DOMContentLoaded', () => {
    const loginForm = document.getElementById('loginForm') as HTMLFormElement;
    const errorMessage = document.getElementById('errorMessage') as HTMLDivElement;

    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const username = (document.getElementById('username') as HTMLInputElement).value;
        const password = (document.getElementById('password') as HTMLInputElement).value;

        try {
            const response = await fetch('/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || '登录失败');
            }

            const data: LoginResponse = await response.json();
            
            // 存储token和登录状态到localStorage
            localStorage.setItem('authToken', data.token);
            localStorage.setItem('isLoggedIn', 'true');
            
            // 登录成功后跳转到首页
            window.location.href = 'index.html';
        } catch (error) {
            errorMessage.textContent = error instanceof Error ? error.message : '登录过程中发生错误';
            console.error('Login error:', error);
        }
    });
});